package com.demo.dbcompare.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.demo.dbcompare.enums.CompareConstant;
import com.demo.dbcompare.factory.MapperCache;
import com.demo.dbcompare.mapper.TableColumnInfoMapper;
import com.demo.dbcompare.model.TableColumnInfo;
import com.demo.dbcompare.model.dto.CompareTastDto;
import com.demo.dbcompare.service.TableColumnInfoService;

@Service
public class TableColumnInfoServiceImpl implements TableColumnInfoService {
	
	@Override
	public List<TableColumnInfo> seizeTableColumnInfo(CompareTastDto compareTast, String connName) {
		List<TableColumnInfo> tableColumnInfoList = new ArrayList<>();

		String dbName = null;
		List<String> tableNameList = null;
		TableColumnInfoMapper tableColumnInfoMapper = null;
		if (connName.equals(CompareConstant.DEFAULT_LEFT_CONN_NAME)) {
			dbName = compareTast.getDbNameLeft();
			tableNameList = compareTast.getTableNameListLeft();
			tableColumnInfoMapper = MapperCache.getTableColumnInfoMapper(compareTast.getConnConfLeft());
		} else if (connName.equals(CompareConstant.DEFAULT_RIGHT_CONN_NAME)) {
			dbName = compareTast.getDbNameRight();
			tableNameList = compareTast.getTableNameListRight();
			tableColumnInfoMapper = MapperCache.getTableColumnInfoMapper(compareTast.getConnConfRight());
		}

		if (tableColumnInfoMapper == null) {
			return tableColumnInfoList;
		}
		if (CollectionUtils.isEmpty(tableNameList)) {
			// 如果页面没有传待比较的表名列表，则根据数据库名查询所有表，然后查询所有列
			tableNameList = new ArrayList<>();
			tableNameList.addAll(tableColumnInfoMapper.findTables(dbName));
		}
		if (CollectionUtils.isNotEmpty(tableNameList)) {
			int fromIndex = 0;
			int size = tableNameList.size();
			while (fromIndex < size) {
				int toIndex = Math.min(fromIndex + CompareConstant.BATCH_TABLE_COUNT, size);
				tableColumnInfoList.addAll(tableColumnInfoMapper.findByTableNameList(tableNameList.subList(fromIndex, toIndex), dbName));
				fromIndex = toIndex;
			}
		}
		return tableColumnInfoList;
	}

}
